package com.woniuxy.hrp.web;


import com.alibaba.fastjson.JSON;
import com.woniuxy.hrp.entity.*;
import com.woniuxy.hrp.mapper.DoctorAndTimeMapper;
import com.woniuxy.hrp.mapper.DoctorMapper;
import com.woniuxy.hrp.mapper.ReservationMapper;
import com.woniuxy.hrp.security.JwtUtil;
import com.woniuxy.hrp.service.ArrangeTimeService;
import com.woniuxy.hrp.service.DoctorService;
import com.woniuxy.hrp.service.ReservationService;
import com.woniuxy.hrp.unityhandler.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @Description：
 * @Author：曹杰克
 * @CreateTime：2022/8/30 14:49
 */
@Transactional
@RestController
@CrossOrigin
@RequestMapping("/api/v1/doctor")
public class DoctorController {
    @Autowired
    private DoctorService doctorService;
    @Autowired
    private DoctorMapper doctorMapper;
    @Autowired
    private DoctorAndTimeMapper doctorAndTimeMapper;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private ArrangeTimeService arrangeTimeService;
    @Autowired
    private ReservationService reservationService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    ReservationMapper reservationMapper;

    @RequestMapping("/getpaiban")
    public ResponseEntity<Doctor> getPaiBan(@RequestHeader String jwt) {
        ResponseEntity<Doctor> result = new ResponseEntity<>();
        int doctorid = (int) jwtUtil.getInfo(jwt, "id");
        Doctor doctor = doctorService.getArrangeTimeById(doctorid);
        List<DoctorAndTime> doctorAndTimes = doctor.getDoctorAndTimes();
        List<ArrangeTime> arrangeTimes = doctor.getArrangeTimes();
        for(int i=0;i<doctorAndTimes.size();i++){
            arrangeTimes.get(i).setMid(doctorAndTimes.get(i).getId());
        }
        doctor.setId(doctorid);
        result.setData(doctor);
        result.setCode("200");
        result.setMsg("成功");
        return result;
    }

    @RequestMapping("/getallpaiban")
    public ResponseEntity<List<ArrangeTime>> getAllPaiBan() {
        ResponseEntity<List<ArrangeTime>> result = new ResponseEntity<>();
        result.setData(arrangeTimeService.getAll());
        result.setCode("200");
        result.setMsg("成功");
        return result;
    }

    @PostMapping("/preAppoint")
    public ResponseEntity preAppoint(@RequestBody PreOv preOv, @RequestHeader String jwt) throws ParseException {
        /**
         * @Author 李国杰
         * @Description //预约实现
         @@ -64,9 +61,32 @@ public class DoctorController {
          * @Param [reservation]
         * @return com.woniuxy.hrp.unityhandler.ResponseEntity<java.lang.String>
         **/

        Pattern s = Pattern.compile(".*" + preOv.getName() + ".*");
        Doctor doctor = new Doctor();
        int doctor_id = 0;
        if (!"".equals(preOv.getName())) {
            for (Doctor d : doctorService.selectAll()) {
                if (s.matcher(d.getName()).matches()) {
                    System.out.println("匹配到的医生id为" + d.getId());
                    doctor_id = d.getId();
                    doctor = d;
                }
                ;
            }
        }
        preOv.setDoctorid(doctor_id);
        System.out.println("获取的日期为" + preOv.getDate());
        String dateTime = preOv.getDate().replace("Z", " UTC");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
        SimpleDateFormat defaultFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date time = format.parse(dateTime);
        System.out.println("修改后的" + defaultFormat.format(time));
        preOv.setDate(defaultFormat.format(time));
        Reservation reservation = new Reservation();
        Patient patient = new Patient();
        patient.setId((Integer) jwtUtil.getInfo(jwt, "id"));
        reservation.setPatient(patient);
        reservation.setStatus("n");
        reservation.setDatetime(defaultFormat.format(time));
        int infor = reservationService.addReservation(reservation, preOv);
        if (infor > 0) {
            return new ResponseEntity<>("200", "success", doctor);
        } else if (infor == -1) {
            return new ResponseEntity<>("500", "不在预约时间", doctor);
        } else if (infor == -2) {
            return new ResponseEntity<>("500", "预约人数已满", doctor);
        } else if (infor == -3) {
            return new ResponseEntity<>("500", "该医生暂时不可预约", doctor);
        } else {
            return new ResponseEntity<>("500", "系统维护中", doctor);
        }

    }

    @RequestMapping("/selecon")
    public ResponseEntity<List<PreOv>> seleByCon(@RequestBody Doctor doctor) {
        /**
         * @Author 李国杰
         * @Description //分条件差医生
         * @Date 10:11 2022/8/31
         * @Param [doctor]
         * @return com.woniuxy.hrp.unityhandler.ResponseEntity<java.util.List < com.woniuxy.hrp.entity.Doctor>>
         **/
        if (redisTemplate.opsForValue().get("depart" + doctor.getDepartment().getId()) == null ||
                JSON.parseArray((String) redisTemplate.opsForValue().get("depart" + doctor.getDepartment().getId()), PreOv.class).size() == 0) {
            System.out.println("进入redis中找不到id为" + doctor.getDepartment().getId() + "部门的医生");
            List<PreOv> preOvs = new ArrayList<>();

            doctorService.seleByCon(doctor).forEach(d -> {

                Doctor doctor1 = doctorMapper.seleAllById(d.getId());
                if (doctor1 != null) {
                    doctor1.getDoctorAndTimes().forEach(r -> {
                        PreOv preOv = new PreOv();
                        preOv.setDate(r.getArrangeTime().getStartTime() + "-" + r.getArrangeTime().getEndTime());
                        preOv.setName(d.getName());
                        if(doctorAndTimeMapper.seleById(r.getId())!=null&&doctorAndTimeMapper.seleById(r.getId()).getReservations().size() < r.getNum()&&"y".equals(r.getStatus())){
                            preOvs.add(preOv);
                        }else if(r.getNum()>1&&doctorAndTimeMapper.seleById(r.getId())==null&&"y".equals(r.getStatus())){
                            System.out.println(preOv.getDate());
                            preOvs.add(preOv);
                        }

                    });
                }
            });
            redisTemplate.opsForValue().set("depart" + doctor.getDepartment().getId(), JSON.toJSONString(preOvs));
            return new ResponseEntity("200", "success", preOvs);
        } else {
            System.out.println("在redis中找到id为" + doctor.getDepartment().getId() + "部门的医生");
            return new ResponseEntity("200", "success", JSON.parseArray((String) redisTemplate.opsForValue().get("depart" + doctor.getDepartment().getId()), PreOv.class));
        }


    }

    @RequestMapping("/getdp")
    public ResponseEntity<List<Doctor>> getDP(@RequestBody Doctor doctor) {
        /**
         * @Author 李国杰
         * @Description //分条件差医生
         * @Date 10:11 2022/8/31
         * @Param [doctor]
         * @return com.woniuxy.hrp.unityhandler.ResponseEntity<java.util.List < com.woniuxy.hrp.entity.Doctor>>
         **/
        System.out.println("查询部门");
        return new ResponseEntity("200", "success", doctorService.getDPById(doctor.getId()));
    }

    @RequestMapping("/api/doctorlogin")
    public ResponseEntity Login(@RequestBody Doctor doctor, HttpServletResponse res) {
        Doctor login = doctorService.login(doctor.getAccount(), doctor.getPassword());
        ResponseEntity result = new ResponseEntity<>();
        if (login != null) {
            String jwt = jwtUtil.createJWT(login.getId(), login.getAccount());
            result.setMsg("登录成功");
            result.setCode("200");
            res.addHeader("jwt", jwt);
            return result;
        } else {
            result.setCode("500");
            result.setMsg("登录失败");
            return result;
        }
    }

    @GetMapping("/getbydoctorid")
    public ResponseEntity<List<Perm>> index(@RequestHeader String jwt) { //获取请求头
        if (jwtUtil.verifyJWT(jwt)) {
            int doctorid = (int) jwtUtil.getInfo(jwt, "id");
            Doctor doctor = doctorService.selectByDoctorId(doctorid);
            List<Perm> menus = doctor.getPerms();
            List<Perm> menus1 = new ArrayList<>();
            for (Perm menu : menus) {
                if (menu.getFid() == null) {
                    menus1.add(menu);
                    List<Perm> sonMenu = new ArrayList<>();
                    for (Perm menu1 : menus) {
                        if (menu.getId().equals(menu1.getFid())) {
                            sonMenu.add(menu1);
                        }
                    }
                    menu.setSubperms(sonMenu);
                }
            }
            ResponseEntity<List<Perm>> entity = new ResponseEntity<>();
            entity.setCode("200");
            entity.setData(menus1);
            entity.setMsg("ok");
            return entity;
        } else {
            return ResponseEntity.FAIL;
        }
    }


    /**
     *@Description 医生功能：根据id查询医生信息
     *@Author TJ
     *@Version 1.0
     **/
    @PostMapping("/selectByDoctorId")
    public ResponseEntity selectDoctor(@RequestBody Doctor doctor){
        Doctor doctor1 = doctorService.selectByDoctorId(doctor.getId());
        return new ResponseEntity<>(ResponseEntity.SUCCESS.getCode(),ResponseEntity.SUCCESS.getMsg(),doctor1);
    }

    /**
     *@Description
     *@Author TJ
     *@Version 1.0
     **/
    @GetMapping("/findDoctor/{id}")
    public ResponseEntity findDoctor(@PathVariable (value = "id")int id){
        Doctor doctor1 = doctorService.selectByDoctorId(id);
        return new ResponseEntity<>(ResponseEntity.SUCCESS.getCode(),ResponseEntity.SUCCESS.getMsg(),doctor1);
    }

    /**
     *@Description 医生功能：修改密码信息
     *@Author TJ
     *@Version 1.0
     **/
    @PostMapping("/updatePassword")
    public ResponseEntity updatePassword(@RequestBody Doctor doctor){
        doctorService.updatePassword(doctor.getId(),doctor.getPassword());
        return new ResponseEntity<>(ResponseEntity.SUCCESS.getCode(),ResponseEntity.SUCCESS.getMsg(),null);
    }

    /**
     * @Description 医生功能：查询出所有的预约信息(包含时间排序)
     * @Author TJ
     * @Version 1.0
     **/
    @PostMapping("findByIdOrderByTime")
    public ResponseEntity findByIdOrderByTime(@RequestBody Doctor doctor) {
        Doctor doctor1 = doctorService.findByIdOrderByTime(doctor.getId());
        return new ResponseEntity<>(ResponseEntity.SUCCESS.getCode(), ResponseEntity.SUCCESS.getMsg(), doctor1.getReservations());
    }

    /**
     * @Description 医生功能：修改患者预约状态
     * @Author TJ
     * @Version 1.0
     **/
    @GetMapping("/updateStatus/{id}")
    public ResponseEntity updateStatus(@PathVariable(value = "id") int id) {
        doctorService.updateStatus(id);
        return new ResponseEntity<>(ResponseEntity.SUCCESS.getCode(), ResponseEntity.SUCCESS.getMsg(), null);
    }

    /**
     * 获取医生的全部病人
     * @param doctorId
     * @return
     */
    @GetMapping("/getPatientByDoctorId")
    public ResponseEntity getPatientByDoctorId(int doctorId){
        Doctor patientByDoctorId = doctorService.getPatientByDoctorId(doctorId);
        List<DoctorAndTime> doctorAndTimes = patientByDoctorId.getDoctorAndTimes();
        List<Reservation> r=new ArrayList<>();
        List<Patient> p=new ArrayList<>();
        for(int i=0;i<doctorAndTimes.size();i++){
            DoctorAndTime doctorAndTime = doctorAndTimes.get(i);
            List<Reservation> reservations = doctorAndTime.getReservations();
            for(int j=0;j<reservations.size();j++){
                p.add(reservations.get(j).getPatient());
            }
        }
        return new ResponseEntity<>("200","ok",p);
    }


    /**
     *@Description 医生功能：根据患者id增加患者药品和数量
     *@Author TJ
     *@Version 1.0
     **/
    @PostMapping("/addPatientMedicine")
    public ResponseEntity addPatientMedicine( @RequestBody DoctorPatientMedicine doctorPatientMedicine,HttpServletRequest request){
        String jwt = request.getHeader("jwt");
        int doctorId = (int) jwtUtil.getInfo(jwt, "id");
        doctorPatientMedicine.setDoctor_id(doctorId);
        doctorService. addPatientMedicine(doctorPatientMedicine);
        return new ResponseEntity<>(ResponseEntity.SUCCESS.getCode(),ResponseEntity.SUCCESS.getMsg(),null);
    }
}
